import $ from 'jquery'
import 'jquery-validation'
import 'jquery-validation/dist/localization/messages_zh'

export const validateOptions = {
  errorElement: 'span',
  errorClass: 'help-block',
  focusInvalid: false,
  highlight: function (element) {
    $(element).closest('.form-group').addClass('has-error')
  },
  success: function (label) {
    label.closest('.form-group').removeClass('has-error')
    label.remove()
  },
  errorPlacement: function (error, element) {
    element.parent('div').append(error)
  },
  submitHandler: function (form) {
    form.submit()
  }
}

export function initValidator(formSelector, rules, messages = {}) {
  return $(formSelector).validate({
    ...validateOptions,
    rules,
    messages
  })
}

// 常用验证规则
export const commonRules = {
  required: true,
  email: {
    required: true,
    email: true
  },
  phone: {
    required: true,
    minlength: 11,
    maxlength: 11,
    digits: true
  },
  url: {
    required: true,
    url: true
  }
} 